<template>
  <div class="image-viewer">
    <h1>当前点击图片信息</h1>
    <div class="image_container" v-if="currentImage && currentImage.url">
      <img :src="currentImage.url" alt="Camera Screenshot" class="image-preview" />
      <p>大棚编号: {{ currentImage.serialNumber }}</p>
      <p>时间: {{ currentImage.time }}</p>
    </div>
    <div v-else>
      <p style="padding-top: 12vw" >点击记录查看图片信息详情</p>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import axios from 'axios';
import { useStore } from '@/store/index.js';

const props = defineProps({
  currentImage: {
    type: Object,
    default: null,
  },
});

const imageUrl = ref('');

watch(
    () => props.currentImage,
    async (newImage) => {
      if (newImage && newImage.localImagePath) {
        imageUrl.value = await getImageUrl(newImage.localImagePath);
      } else {
        imageUrl.value = '';
      }
    },
    { immediate: true }
);

// 获取图片 URL
const getImageUrl = async (localImagePath) => {
  const userStore = useStore();
  const token = userStore.token;
  const relativePath = convertToRelativePath(localImagePath);
  const filename = relativePath.split('/').pop();

  try {
    const response = await axios.get(`/api/camera_data/image/${filename}`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      responseType: 'arraybuffer',
    });

    const binaryString = Array.from(new Uint8Array(response.data))
        .map((byte) => String.fromCharCode(byte))
        .join('');
    const base64 = btoa(binaryString);
    return `data:image/jpeg;base64,${base64}`;
  } catch (error) {
    console.error('获取图片失败:', error);
    return '';
  }
};

// 将绝对路径转换为相对路径
const convertToRelativePath = (absolutePath) => {
  const projectRoot = "C:\\Users\\user\\Desktop\\ShiXun\\TiXiJieGou\\achitecture\\src\\main\\resources\\image\\";
  if (absolutePath.startsWith(projectRoot)) {
    return absolutePath.substring(projectRoot.length);
  }
  return absolutePath;
};
</script>

<style scoped>
.image-viewer {
  padding: 20px;
  background-color: #1e2a38;
  color: #f1f1f1;
  border-radius: 12px;
  //margin-top: 20px;
  height: 645px;
  width: 670px;
  box-shadow: 0 0 20px 5px rgb(22, 92, 194);
}
.image_container{
  margin-top: 4vw;
}
.image-preview {
  width:650px;
  height:370px;
  object-fit: cover;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

h1 {
  color: #417fd9;
  font-size: 22px;
  margin-bottom: 10px;
}

p {
  margin: 50px 0;
}
</style>